<template>
  <!-- 角色列表 -->
  <div>
    <el-button type="primary" size="small" @click="open(null)">新增</el-button>
    <p
      style="
        font-size: 20px;
        font-weight: bold;
        width: 400px;
        margin: 0 auto;
        text-align: center;
        margin-top: 20px;
      "
    >
      角色显示列表
    </p>
    <el-table
      :data="roleList"
      border
      style="width: 800; margin: 0 auto; margin-top: 40px"
    >
      <el-table-column label="角色名称" width="180">
        <template v-slot="scoped">
          <a href="#" @click="save(scoped.row.roleName, scoped.row.roleId)">{{
            scoped.row.roleName
          }}</a>
        </template>
      </el-table-column>
      <el-table-column prop="createName" label="创建人" width="180" />
      <el-table-column prop="createTime" label="创建时间">
        <template v-slot="scoped">
          {{ scoped.row.createTime.substring(0, 10) }}
        </template>
      </el-table-column>
      <el-table-column prop="updateName" label="修改人" />
      <el-table-column prop="updateTime" label="修改时间">
        <template v-slot="scoped">
          {{
            scoped.row.updateTime ? scoped.row.updateTime.substring(0, 10) : ""
          }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="235">
        <template v-slot="scoped">
          <el-button type="warning" size="small" @click="open(scoped.row)"
            >修改</el-button
          >
          <el-button type="danger" size="small" @click="Del(scoped.row.roleId)"
            >删除</el-button
          >
          <el-button
            type="success"
            size="small"
            @click="FenPei(scoped.row.roleId, scoped.row.roleName)"
            >分配人员</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!-- 部门对应的员工——分配 -->
  <div>
    <el-dialog v-model="dialogFormVisible" title="部门对应员工" width="500">
      <p>
        请设置 <span style="color: red">【{{ roleNames }}】</span>的员工
      </p>
      <template #footer>
        <div class="dialog-footer">
          <el-container>
            <el-aside style="height: 300px; width: 200px">
              <!-- 部门加载 -->
              <div>
                <div>
                  <el-tree
                    :data="DepData"
                    show-checkbox
                    node-key="value"
                    ref="treeRef"
                    :props="defaultProps"
                    @check-change="handleCheckChange"
                    :default-checked-keys="defaultCheckedKeys"
                  ></el-tree>
                </div>
              </div>
            </el-aside>
            <el-aside style="height: 300px; width: 200px">
              <!-- 用户根据部门加载 -->
              <div>
                <p>选择员工</p>
                <el-checkbox-group
                  v-model="userrolevules.userIds"
                  placeholder="选择员工"
                >
                  <el-checkbox
                    v-for="items in uservule"
                    :key="items.userId"
                    :label="items.userName"
                    :value="items.userId"
                  />
                </el-checkbox-group>
                <!-- {{ userrolevules.userIds }} -->
              </div>
            </el-aside>
          </el-container>

          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="RoleUserAdd()"> 保存 </el-button>
        </div>
      </template>

      <!-- 角色对应的用户弹出框 -->
    </el-dialog>
    <div>
      <div>
        <el-dialog
          v-model="dialogFormVisible2"
          title="角色对应的用户"
          width="500"
        >
          <h3>
            属于角色<span style="color: red"
              >【{{ roleNames }}】的员工如下</span
            >
          </h3>

          <el-table :data="getUserNamelist" border style="width: 100%">
            <el-table-column prop="roleName" label="角色名称" width="180" />
            <el-table-column prop="userName" label="员工名称" width="180" />
            <el-table-column label="操作">
              <template v-slot="scoped">
                <el-button
                  type="danger"
                  size="small"
                  @click="Delur(scoped.row.ruId)"
                  >×</el-button
                >
                <el-button
                  type="success"
                  size="small"
                  style="margin-top: 5px"
                  @click="roleUserCor(scoped.row.roleid, scoped.row.roleName)"
                  >+</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="dialogFormVisible2 = false">关闭</el-button>
            </div>
          </template>
        </el-dialog>
      </div>
    </div>
  </div>

  <!-- 新增 -->
  <div>
    <el-dialog
      v-model="Eject.dialogFormVisible"
      :title="Eject.title"
      width="800px"
    >
      <el-form
        ref="ruleFormRef"
        style="max-width: 350px; margin-left: 400px"
        :model="form"
        label-width="auto"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm"> 保存 </el-button>
             <el-button @click="Eject.dialogFormVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import axios, { Axios } from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import moment from "moment";
import { onMounted, reactive, ref, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useCounterStore } from "@/stores/counter";
import DepData from "@/stores/departmentData";
import { da } from "element-plus/es/locales.mjs";
const store = useCounterStore();
const router = useRouter();

const page = reactive({
  pageIndex: 1,
  pageSize: 15,
  totalCount: 0,
  totalPage: 0,
});

//#region  角色列表
const roleList = ref([]);
// 角色显示列表
const getroleList = () => {
  axios
    .get("https://localhost:7174/api/Message/GetRole", {
      params: {
        PageIndex: page.pageIndex,
        PageSize: page.pageSize,
      },
    })
    .then((res) => {
      //console.log(res.data)
      roleList.value = res.data.data;
      page.totalCount = res.data.totalCount;
      page.totalPage = res.data.totalPage;
    });
};

onMounted(() => {
  getroleList(); // 获取角色列表
});

//修改页面跳转——UpdateRole
/* const Updatedata = (ids: any) => {
  console.log(ids);
  store.ccstore.uproleId = ids; //将id传给store(pinia)
  router.push({
    name: "UpdateRole",
  });
}; */

//删除角色
const Del = (ids: any) => {
  ElMessageBox.confirm("你确定删除吗?", "提示", {
    confirmButtonText: "删除",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      axios
        .post("https://localhost:7272/api/Message/DelRole", {
          roleId: ids,
        })
        .then((res) => {
          if (res.data.code == 204) {
            ElMessage.success(res.data.msg);
            getroleList();
          }
        });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
    });
};

//#endregion

const roleNames = ref("");
const dialogFormVisible = ref(false);

// 分配角色
const FenPei = (roleId: any, roleName: any) => {
  dialogFormVisible.value = true;
  userrolevules.roleId = roleId;
  console.log(roleId, " 角色ID");
  roleNames.value = roleName;

  console.log(roleNames.value, " 角色名称");
  fenpeiuserromedep(roleId);
  clear();
};

//清空已经分配的角色
const clear = () => {
  defaultCheckedKeys.value = [];
  Depidvalue.value = [];
};

//获取部门对应的员工名称
// const defaultCheckedKeys = ref<any>([]);
const fenpeiuserromedep = (roleids: any) => {
  // alert(roleids)
  defaultCheckedKeys.value = [];
  console.log(defaultCheckedKeys.value, "默认选中");
  Depidvalue.value = [];

  axios
    .get("https://localhost:7174/api/Message/UserRoledep/UserRoledep", {
      params: { roleid: roleids },
    })
    .then((res) => {
      const data = res.data.data;
      //反填用户
      const userids = data.map((x: any) => x.userId);
      // 设置默认选中的用户ID
      userrolevules.userIds = userids;

      // console.log(userids, '反填用户ids')
      // 获取部门ID并去重
      const depids = data.map((x: any) => x.depId);
      // console.log(depids, "反填部门ids");
      const depIdVule = [...new Set(depids)];

      // console.log(depIdVule, '反填部门ids')
      defaultCheckedKeys.value = depIdVule;
    });
};

//树形控价
const defaultProps = {
  children: "children",
  label: "label",
};

//选中的节点
const defaultCheckedKeys = ref<any>([]);
const treeRef = ref();

//选中的部门id
const Depidvalue = ref<any>([]);
//点击部门获取对应的员工
const handleCheckChange = () => {
  //获取部门选中的id --数组
  const selectedDepIds = treeRef.value.getCheckedKeys().join(",");
  // console.log(selectedDepIds, "选中的部门id");
  if (!selectedDepIds) return;
  //   console.log(aa);
  axios
    .get("https://localhost:7174/api/Message/GetUserNameByDepId", {
      params: {
        DepId: selectedDepIds,
      },
    })
    .then((res) => {
      uservule.value = res.data.data;
    });
};

//获取用户数据列表
const uservule = ref();

//添加用户角色数据
const userrolevules = reactive({
  userRoleId: 0,
  roleId: 0,
  userIds: [],
});

// 保存角色与之部门对应的用户名称
const RoleUserAdd = () => {
  roleUserCor; //保存角色与部门对应关系

  // 1、通过角色ID 批量删除

  // 2、批量添加
  axios
    .post("https://localhost:7272/api/Message/PLAdd", userrolevules)
    .then((res) => {
      if (res.data.code == 214) {
        ElMessage.success(res.data.msg);
        dialogFormVisible.value = false;
      } else {
        ElMessage.success(res.data.msg);
      }
    });
  dialogFormVisible.value = false;
};

const dialogFormVisible2 = ref(false);
const roleValues = reactive({
  roleId: 0,
  roleIdName: "",
});

const save = (roleName: any, roleId: any) => {
  userrolevules.roleId = roleId;
  // console.log(userrolevules.roleId);
  dialogFormVisible2.value = true;
  roleValues.roleId = roleId;
  // console.log(ckrole.ckroleId);
  roleValues.roleIdName = roleName;
  getroleuserList();
};

const getUserNamelist = ref<any>([]);

//点击角色名称查看用户列表
const getroleuserList = () => {
  axios
    .get("https://localhost:7174/api/Message/GetUserNameByRoleId", {
      params: {
        RoleId: roleValues.roleId,
      },
    })
    .then((res) => {
      getUserNamelist.value = res.data.data;
    });
};

//删除角色对应的用户
const Delur = (ids: number) => {
  console.log(ids, "删除角色对应的用户ID");
  ElMessageBox.confirm("你确定删除吗?", "提示", {
    confirmButtonText: "删除",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      axios
        .put("https://localhost:7272/api/Message/DelUR", {
          ruId: [ids],
        })
        .then((res) => {
          if (res.data.code == 204) {
            ElMessage.success(res.data.msg);
            getroleuserList();
          }
        });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
    });
};
const pproleName = ref("");
const roleUserCor = (roleId: any, roleName: any) => {
  //打开分配角色对话框
  dialogFormVisible.value = true;
  FenPei(roleId, roleName);
  pproleName.value = roleName;
  console.log(pproleName.value, "pproleName");
};

const Eject = reactive({
  dialogFormVisible: false,
  title: "",
  formLabelWidth: "120px",
  Isture: true,
});
const form = reactive({
  roleId: 0,
  roleName: "",
  createName: store.ccstore.userName,
  createTime: new Date(),
  /* updateName: null,
  updateTime: null, */
  isDel: false,
});

const open = (row: any) => {
  if (row == null) {
    Eject.dialogFormVisible = true;
    Eject.title = "添加用户";
    Eject.Isture = true;
    form.roleId = 0;
    (form.roleName = ""),
      (form.createName = store.ccstore.userName),
      (form.createTime = new Date()),
  /*     (form.updateName = null),
      (form.updateTime = null), */
      (form.isDel = false);
  } else {
    Eject.dialogFormVisible = true;
    Eject.title = "修改用户";
    Eject.Isture = false;
    form.roleId = row.roleId;
    form.roleName = row.roleName;
    form.createName = row.createName;
    form.createTime = row.createTime;
    form.updateName = store.ccstore.userName;
    form.updateTime = row.updateTime;
    form.isDel = row.isDel;
  }
};

// 添加、修改角色
const submitForm = () => {
  if (Eject.Isture) {
    axios
      .post("https://localhost:7272/api/Message/AddRole", form)
      .then((res) => {
        if (res.data.code == 100) {
          console.log(res.data);
          ElMessage.success(res.data.msg);
   Eject.dialogFormVisible = false;
          getroleList();
        } else {
          if (res.data.data == 0) {
            ElMessage.error("角色名称不能重复");
            return;
          } else {
            ElMessage.error("添加失败");
            return;
          }
        }
      });
  } else {
    axios
      .post("https://localhost:7272/api/Message/UpDateRole", form)
      .then((res) => {
        if (res.data.code == 206) {
          ElMessage.success(res.data.msg);
         Eject.dialogFormVisible = false;
          getroleList();
        } else {
          if (res.data.code == 209) {
            ElMessage.error(res.data.msg);
            Eject.dialogFormVisible = false;
            getroleList();
            return;
          } else {
            ElMessage.error(res.data.msg);
            return;
          }
        }
      });
  }
};
</script>
<style scoped>
</style>